﻿using System.Data.SqlClient;
using GeneralLibs;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;
using DevExpress.Utils;
using DevExpress.XtraGrid;

namespace ReportGenerators.QuanLyKho.ThongKeTonTheoNhaCungCap
{
    public partial class FrmThongKeTonTheoNhaCungCapHuyHoangSG : BasicForms.FrmSupportPrintableComponents
    {
        public FrmThongKeTonTheoNhaCungCapHuyHoangSG()
        {
            InitializeComponent();
        }

        private void FrmThongKeTonTheoNhaCungCap_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            cmbNhaCungCap.PopupWidth = 500;
            cmbNhaCungCap.PopupHeight = 200;
            try
            {
                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                cmbNhaCungCap.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView;
                cmbNhaCungCap.DisplayColumn = "Ten";
                cmbNhaCungCap.ValueColumn = "ID";
                cmbNhaCungCap.AddVisibleColumn("Ma", "Mã", 40);
                cmbNhaCungCap.AddVisibleColumn("Ten", "Tên", 300);

                //cmbKyBaoCao.SelectedIndex = 17;
                cmbKyBaoCao.Text = "Tùy chọn";
                txtGioiHanSoLuongTon.EditValue = 1000000000;

                if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("HUYHOANGSG"))
                {
                    colNgayNhapDau.Visible = true;
                    colNgayNhapCuoi.Visible = true;
                }
                else
                {
                    colNgayNhapDau.Visible = false;
                    colNgayNhapCuoi.Visible = false;
                }


                cmbNhaCungCap.EditValue = Guid.Empty;
                dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangGanVoiNhaCungCap_TruHangKhongDung((Guid)cmbNhaCungCap.EditValue).DataView.ToTable());
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            chkChooseAllVatTuHangHoa.Checked = false;

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewShow.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }

            FormatTextEdit(txtGioiHanSoLuongTon, TextFormatType.Money);
            FormatNumberInGridView(gridViewDsVatTuHangHoa);
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }

        private void cmbNhaCungCap_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhaCungCap.EditValue = Guid.Empty;
        }
        private void cmbNhaCungCap_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbNhaCungCap.EditValue is Guid && (Guid)cmbNhaCungCap.EditValue != Guid.Empty)
                {
                    dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Clear();
                    //Lấy những hàng đã mua.
                    dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangGanVoiNhaCungCap((Guid)cmbNhaCungCap.EditValue).DataView.ToTable());
                }
                else
                {
                    dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Clear();
                    //dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
                }
                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Rows)
                {
                    row["Choose"] = true;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
                gridControlDsVatTuHangHoa.DataSource = dsThongKeTonTheoNhaCungCap.VatTuHangHoa;
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            int gioiHanSoLuong = (int)txtGioiHanSoLuongTon.EditValue;

            Guid khoID = Guid.Empty;
            if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty)
                khoID = (Guid)cmbKho.EditValue;

            Guid doiTuongNghiepVuID = Guid.Empty;
            if (!(cmbNhaCungCap.EditValue is Guid) && (Guid)cmbNhaCungCap.EditValue == Guid.Empty)
            {
                MessageBox.Show("Phải chọn nhà cung cấp");
            }
            else
            {
                doiTuongNghiepVuID = (Guid)cmbNhaCungCap.EditValue;
            }

            BasicForms.FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand(); cmd.CommandTimeout = Config.TimeOut;

                dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Clear();

                int count = 0;
                int total = dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Select("Choose = 1").Length;

                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.VatTuHangHoa.Rows)
                {
                    if (row["Choose"] is bool && (bool)row["Choose"])
                    {
                        BasicForms.FrmProgressBar.Status = string.Format("Đang xử lý {0}/{1}", count, total);
                        count++;

                        Guid vatTuHangHoaID = (Guid)row["ID"];
                        VatTuHangHoa vatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID(vatTuHangHoaID);
                        ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayBatDau);

                        TonKho tonDauKy = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(cmd, thoiDiemKhoaSoGanNhat.ThoiDiem.AddSeconds(2), vatTuHangHoaID);
                        TonKho tonKho = new TonKho();
                        TonKho xuatTra = new TonKho();
                        TonKho phatSinhNhap = new TonKho();
                        TonKho phatSinhXuat = new TonKho();

                        if (khoID == Guid.Empty)
                        {
                            tonKho = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(ngayKetThuc, vatTuHangHoaID);
                            xuatTra = TonKho.CalculatePhatSinhXuatTraMatHang(cmd, ngayBatDau, ngayKetThuc, (Guid)cmbNhaCungCap.EditValue, vatTuHangHoaID);
                            phatSinhNhap = TonKho.CalculatePhatSinhNhapToanBoByHangHoaAndNCC(cmd, ngayBatDau, ngayKetThuc, doiTuongNghiepVuID, vatTuHangHoaID);
                            phatSinhXuat = TonKho.CalculatePhatSinhXuatToanBo(cmd, ngayBatDau, ngayKetThuc, vatTuHangHoaID);
                        }
                        else
                        {
                            tonKho = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, ngayKetThuc, khoID, vatTuHangHoaID);
                            xuatTra = TonKho.CalculatePhatSinhXuatTraMatHangTheoKho(cmd, ngayBatDau, ngayKetThuc, khoID, (Guid)cmbNhaCungCap.EditValue, vatTuHangHoaID);
                            phatSinhNhap = TonKho.CalculatePhatSinhNhapByHangHoaAndNCC(cmd, ngayBatDau, ngayKetThuc, khoID, doiTuongNghiepVuID, vatTuHangHoaID);
                            phatSinhXuat = TonKho.CalculatePhatSinhXuat(cmd, ngayBatDau, ngayKetThuc, khoID, vatTuHangHoaID);
                        }

                        //decimal donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonTrungBinhTheoGiaTriConLaiToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc); //trung bình còn lại
                        decimal donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonNhapTrungBinhToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, thoiDiemKhoaSoGanNhat.ThoiDiem, ngayKetThuc);  // Trung bình mua vào
                        //Nếu giá vốn mua vào trong khoảng thời gian này = 0 (k mua) thì tính trung bình còn lại
                        if (donGiaVon <= 0)
                            donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonTrungBinhTheoGiaTriConLaiToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, thoiDiemKhoaSoGanNhat.ThoiDiem, ngayKetThuc); //trung bình còn lại

                        if (tonKho.SoLuong < gioiHanSoLuong)
                        {
                            DataRow addedRow = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.NewRow();

                            addedRow["Ma"] = vatTuHangHoa.Ma;
                            addedRow["Ten"] = vatTuHangHoa.Ten;
                            addedRow["GiaBia"] = vatTuHangHoa.GiaBia;
                            addedRow["TenNhomVatTuHangHoa"] = DanhMucNhomVatTuHangHoa.Instance.GetByID(vatTuHangHoa.NhomVatTuHangHoa.ID).Ten;
                            addedRow["SoLuongTonDauKy"] = tonDauKy.SoLuong;
                            addedRow["SoLuongNhap"] = phatSinhNhap.SoLuong;
                            addedRow["GiaTriNhap"] = phatSinhNhap.ThanhTien;
                            addedRow["SoLuongXuat"] = phatSinhXuat.SoLuong - xuatTra.SoLuong;
                            addedRow["GiaTriXuat"] = phatSinhXuat.ThanhTien - xuatTra.ThanhTien;
                            addedRow["SoLuongXuatTra"] = xuatTra.SoLuong;
                            addedRow["GiaTriXuatTra"] = xuatTra.ThanhTien;
                            addedRow["SoLuongTon"] = tonKho.SoLuong;
                            addedRow["GiaTriTongTon"] = donGiaVon * tonKho.SoLuong;

                            //Tính riêng cho Huy Hoàng SG
                            if (DanhMucStore.Instance.CurrentStore().Ten.ToUpper().Contains("HUYHOANGSG"))
                            {
                                List<DateTime?> date = new List<DateTime?>();
                                date = FindDateNhapByHangHoaAndNCC(cmd, doiTuongNghiepVuID, vatTuHangHoa.ID);
                                if (date[0] != null) addedRow["NgayNhapDau"] = date[0];
                                if (date[1] != null) addedRow["NgayNhapCuoi"] = date[1];
                            }

                            dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Rows.Add(addedRow);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
                BasicForms.FrmProgressBar.FinishShowProgress();
            }

            gridControlShow.DataSource = AlphabeticSort(dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap, "TenNhomVatTuHangHoa", 0).DefaultView; //Sort theo nhom hang
            FormatNumberInGridView(gridViewShow);
            FormatNumberInGridView(gridViewDsVatTuHangHoa);
        }

        public static List<DateTime?> FindDateNhapByHangHoaAndNCC(SqlCommand cmd, Guid doiTuongNghiepVuID, Guid vatTuHangHoaID) //Trả về ngày nhập đầu tiền và cuối cùng theo đối tác và hàng hóa
        {
            try
            {
                DateTime? minDate = null;
                DateTime? maxDate = null;

                cmd.CommandText = string.Format("SELECT MIN(Ngay) MinDate, MAX(Ngay) MaxDate \n" +
                                            "FROM NhatKyNhapKho \n" +
                                            "WHERE VatTuHangHoaID = '{0}' AND DoiTuongNghiepVu1ID = '{1}'",
                                            vatTuHangHoaID, doiTuongNghiepVuID);

                cmd.Parameters.Clear();
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    if (dr["MinDate"] is DateTime)
                    {
                        try
                        {
                            minDate = Convert.ToDateTime(dr["MinDate"]);
                        }
                        catch (Exception ex)
                        { }
                    }
                    if (dr["MaxDate"] is DateTime)
                    {
                        try
                        {
                            maxDate = Convert.ToDateTime(dr["MaxDate"]);
                        }
                        catch (Exception ex)
                        { }
                    }
                }
                dr.Close();

                //Nếu min == max --> gán max bằng null để hiện 1 ngày thôi
                if (minDate != null && maxDate != null && DateTime.Compare(Convert.ToDateTime(minDate), Convert.ToDateTime(maxDate)) == 0)
                {
                    maxDate = null;
                }

                return new List<DateTime?> { minDate, maxDate };
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            printableComponentLink1.Component = gridControlShow;
            printableComponentLink1.PaperKind = System.Drawing.Printing.PaperKind.A4;
            //printableComponentLink1.CreateReportHeaderArea +=  new CreateAreaEventHandler(printableComponentLink1_CreateReportHeaderArea);
            printableComponentLink1.ShowPreview();
            //gridControlShow.ShowPrintPreview();
        }
        private void printableComponentLink1_CreateReportHeaderArea(object sender, CreateAreaEventArgs e)
        {
            string reportHeader = "Dat hang";
            e.Graph.StringFormat = new BrickStringFormat(StringAlignment.Near);
            e.Graph.Font = new Font("Tahoma", 14, FontStyle.Bold);
            RectangleF rec = new RectangleF(0, 0, e.Graph.ClientPageSize.Width, 50);
            e.Graph.DrawString(reportHeader, Color.Black, rec, BorderSide.None);
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private DataTable AlphabeticSort(DataTable dtTable, string sortColumn, int sortOrder)
        {
            DataSet dsSorted = new DataSet();
            string columnKey = sortColumn;
            string sortDirection = "";
            string sortFormat = "{0} {1}";
            switch (sortOrder)
            {
                case 0:
                    sortDirection = "ASC";
                    break;
                case 1:
                    sortDirection = "DESC";
                    break;
                default:
                    sortDirection = "ASC";
                    break;
            }

            dtTable.DefaultView.Sort = string.Format(sortFormat, columnKey, sortDirection);

            return dtTable.DefaultView.Table;
        }

        private void cmbKho_EditValueChanged(object sender, EventArgs e)
        {
        }
    }
}

